// import PropTypes from 'prop-types'
import React, { memo, useEffect, useRef, useState } from 'react'
import { LeftOutlined, RightOutlined } from '@ant-design/icons'
import { ScrollWrapper } from './style'

const ScrollView = memo((props) => {
  const [showLeft, setShowLeft] = useState(false)
  const [showRight, setShowRight] = useState(false)
  const [posIndex, setPosIndex] = useState(0)

  const scrollContentRef = useRef();
  const totalDistanceRef = useRef();
  useEffect(()=>{
    const clientWidth = scrollContentRef.current.clientWidth;
    const scrollWidth = scrollContentRef.current.scrollWidth;
    const distance = scrollWidth - clientWidth;
    totalDistanceRef.current = distance
    setShowRight(totalDistanceRef.current > 0&&posIndex===0)
  },[posIndex, props.children])

  function controllClickHandle(isRight){
    const newPosIndex = isRight?posIndex+1:posIndex-1;
    const newOffsetLeft = scrollContentRef.current.children[newPosIndex].offsetLeft
    const diff = newOffsetLeft - totalDistanceRef.current
    const PX = diff > 0 ? totalDistanceRef.current : newOffsetLeft
    setPosIndex(newPosIndex)
    scrollContentRef.current.style.transform = `translateX(-${PX}px)`
    setShowRight(newOffsetLeft < totalDistanceRef.current)
    // setShowLeft(PX!==0 )
    setShowLeft(newPosIndex!==0 )
  }

  return (
    <ScrollWrapper>
      {showLeft && <div className="left" onClick={e => controllClickHandle(false)}>
        <div className="icon">
            <LeftOutlined />
        </div>
      </div>}
      <div className="scroll">
        <div className="scroll-content" ref={scrollContentRef} >
          {props.children}
        </div>
      </div>
      {showRight && <div className="right" onClick={e => controllClickHandle(true)}>
        <div className="icon" >
          <RightOutlined />
        </div>
      </div>}
    </ScrollWrapper>
  )
})

// index.propTypes = {}

export default ScrollView